<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2025/7/12
 * Time: 15:56
 */

namespace app\controller;


use app\model\Image;

class Api extends Base
{
    public function fileimage(){
        $id = input('id',0);
        $image = input('image');
        $title = input('title','');
        $info = input('info','');
        $sort = input('sort','');
        $url = input('url','');
        if (empty($image))
            return $this->fail('图片必须上传');
        $data = str_replace(' ', '+', $image);
//        $data = $this->compressBase64Image($data,1048576 * 2.5);
//        $data = base64_decode(explode(',',$data['data'])[1]);
        $data = explode(',',$data);
        if (!empty($data[1]))
            $image_base64 = base64_decode($data[1]);
        if (!empty($id)) {
            $image = Image::find($id);
            if (!empty($image->id)) {
                if (!empty($image_base64)) {
                    $uniqid = md5(rand(100,999).time());
                    $filePath = '.' . str_replace($image->name,$uniqid,$image->src);
                    @file_put_contents($filePath, $image_base64);
                }
                $image->save([
                    'title' => $title,
                    'info' => $info,
                    'sort' => $sort,
                    'url' => $url,
                    'status' => 0
                ]);
                $filePath = str_replace('./','/',$filePath);
                return $this->msg($image,$filePath ?? $image->src);
            }
        }
        if (empty($image_base64))
            return $this->fail('图片参数必须填写');
        $uploadDir = './static/upload/' . date('Ymd') . '/';
        if (!is_dir($uploadDir))
            mkdir($uploadDir, 0777, true);
        $filename = md5(uniqid().rand(100,999));
        $filePath = $uploadDir . $filename.'.png';
        @file_put_contents($filePath, $image_base64);
        $filePath = str_replace('./','/',$filePath);
        $image = Image::create([
            'src' => $filePath,
            'name' => $filename,
            'title' => $title,
            'info' => $info,
            'url' => $url,
            'sort' => $sort
        ]);
        return $this->msg($image,$filePath);
    }

    function compressBase64Image($base64Data, $maxSize = 1048576) {
        // 检查是否为有效的Base64数据
        if (!preg_match('/^data:image\/(\w+);base64,/', $base64Data, $matches)) {
            return ['error' => '无效的Base64图片数据'];
        }

        $mimeType = $matches[1]; // 获取图片类型 (jpeg, png, gif)
        $imageData = base64_decode(str_replace($matches[0], '', $base64Data));

        // 创建临时图像资源
        $image = imagecreatefromstring($imageData);
        if (!$image) {
            return ['error' => '无法创建图像资源'];
        }

        // 获取原始尺寸
        $originalWidth = imagesx($image);
        $originalHeight = imagesy($image);

        // 计算压缩比例
        $ratio = sqrt($maxSize / strlen($imageData)); // 平方根保持宽高比
        $newWidth = (int)($originalWidth * $ratio);
        $newHeight = (int)($originalHeight * $ratio);

        // 创建新图像
        $newImage = imagecreatetruecolor($newWidth, $newHeight);

        // 处理透明度（PNG/GIF）
        if ($mimeType == 'png' || $mimeType == 'gif') {
            imagecolortransparent($newImage, imagecolorallocatealpha($newImage, 0, 0, 0, 127));
            imagealphablending($newImage, false);
            imagesavealpha($newImage, true);
        }

        // 调整大小
        imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

        // 保存到临时内存
        ob_start();
        switch ($mimeType) {
            case 'jpeg':
                $quality = 85; // 初始质量
                do {
                    ob_clean();
                    imagejpeg($newImage, null, $quality);
                    $compressedData = ob_get_clean();
                    $quality -= 5;
                } while (strlen($compressedData) > $maxSize && $quality >= 10);
                break;
            case 'png':
                $compressionLevel = 6; // 中等压缩
                ob_clean();
                imagepng($newImage, null, $compressionLevel);
                $compressedData = ob_get_clean();
                break;
            case 'gif':
                ob_clean();
                imagegif($newImage);
                $compressedData = ob_get_clean();
                break;
            default:
                imagedestroy($image);
                imagedestroy($newImage);
                return ['error' => '不支持的图片格式'];
        }

        // 释放内存
        imagedestroy($image);
        imagedestroy($newImage);

        // 检查最终大小
        if (strlen($compressedData) > $maxSize) {
            return ['error' => '无法将图片压缩到指定大小'];
        }

        // 重新编码为Base64
        $compressedBase64 = 'data:image/' . $mimeType . ';base64,' . base64_encode($compressedData);

        return [
            'success' => true,
            'data' => $compressedBase64,
            'originalSize' => strlen($imageData),
            'compressedSize' => strlen($compressedData)
        ];
    }

    function video(){

    }
}